<template>
  <div class="pop-dialog-container">
    <div class="pop-dialog-main">
      <el-form :inline="true" :model="roomQueryForm" ref="roomQueryFormRef" :rules="rules">
        <el-form-item label="楼栋名称" prop="buildingName">
          <el-input v-model="roomQueryForm.buildingName" placeholder="请选择楼栋名称" readonly="readonly">
            <template #suffix>
              <el-icon @click="findBuilding"><Search/></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="房号" prop="roomNumber">
          <el-input v-model="roomQueryForm.roomNumber" placeholder="请输入房号" maxlength="32"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="state.tableData"
        border
        v-loading="state.loading"
        size="small"
        header-cell-class-name="table-header-cell-font"
        cell-class-name="table-cell-font"
        @row-dblclick="roomSelected">
        <el-table-column prop="buildingName" label="楼栋名称"></el-table-column>
        <el-table-column prop="roomNumber" label="房号"></el-table-column>
        <el-table-column prop="floorNumber" label="所在楼层"></el-table-column>
        <el-table-column prop="grossFloorArea" label="建筑面积"></el-table-column>
        <el-table-column prop="netFloorArea" label="实用面积"></el-table-column>
      </el-table>
      <div class="table-pagination">
        <el-pagination
          @current-change="changePage"
          :current-page="state.currentPage"
          :page-sizes="state.pageSizes"
          :page-size="state.pageSize"
          background
          layout="total, prev, pager, next, jumper"
          :total="state.total">
        </el-pagination>
      </div>
    </div>
    <div class="pop-dialog-footer">
      <el-row>
        <el-col :span="11" :offset="6">
          <div class="form-button-container">
            <el-button type="primary" @click="onBack">关闭</el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <el-dialog v-model="buildingSelectorVisible" v-if="buildingSelectorVisible" title="楼栋信息选择器(双击行选中)" :top="dialogTop" :width="dialogWidth">
      <building-selector @building-selected-event="handleBuildingSelectedEvent">
      </building-selector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { defineEmits, inject, onMounted, reactive, ref, toRefs } from 'vue'
import roomApi from '@/api/roomApi'
import type {RoomQueryForm} from "@/types/req/roomQueryForm";
import type {Room} from "@/types/resp/room";
import {type FormInstance} from "element-plus";
import type {Result} from "@/types/result";
import type {Page} from "@/types/page";
import { Search } from '@element-plus/icons-vue';
import BuildingSelector from "@/views/building/BuildingSelector.vue";

const roomQueryFormRef = ref<FormInstance | null>(null);
const roomQueryForm = reactive<RoomQueryForm>({
  buildingId: 0,
  buildingName: '',
  roomNumber: '',
})
const buildingSelectorVisible = ref<boolean>(false)

const state = reactive({
  loading: false,
  tableData: [] as Room[], // 数据列表
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  pageSizes: [10, 20, 50]
})

const dialogTop = ref<string>('')
const dialogWidth = ref<string>('')

const rules = reactive({
});

const emit = defineEmits<{
  (e: 'roomSelectedEvent', data?: {
    roomId: number,
    residentRoomId: number,
    roomNumber: string,
    residentRoomNumber: string,
    }): void;
}>()

onMounted(() => {
  onSearch()
  const globalState = inject('globalState', {} as { dialogWidth?: string, dialogTop?: string })
  if (!globalState) {
    throw new Error('globalState is not provided');
  }
  const globalStateRefs = toRefs(globalState)
  if (globalStateRefs.dialogWidth) {
    dialogWidth.value = globalStateRefs.dialogWidth.value || ''
  }
  if (globalStateRefs.dialogTop) {
    dialogTop.value = globalStateRefs.dialogTop.value || ''
  }
})

const getPageData = async () => {
  try {
    state.loading = true
    const resp: Result<Page<Room>> = await roomApi.find(roomQueryForm)
    if (resp && resp.code === 1) {
      if (resp.data) {
        const page: Page<Room> = resp.data
        if (page && page.list.length > 0) {
          state.tableData = page.list
          state.total = page.total
        }
      }
    }
  } catch (e) {
    console.log('获取数据异常', e)
  } finally {
    state.loading = false
  }
}
const onSearch = () => {
  getPageData()
}

const changePage = (val: number) => {
  state.currentPage = val
  getPageData()
}

const onReset = () => {
  if (roomQueryFormRef.value) {
    roomQueryFormRef.value.resetFields()
  }
  state.currentPage = 1
  getPageData()
}

const roomSelected = (row: Room) => {
  emit('roomSelectedEvent', {
    roomId: row.id,
    residentRoomId: row.id,
    roomNumber: row.roomNumber,
    residentRoomNumber: row.roomNumber,
  })
}

const findBuilding = () => {
  buildingSelectorVisible.value = true
}

const handleBuildingSelectedEvent = (selectedBuilding: any) => {
  buildingSelectorVisible.value = false
  if (selectedBuilding && 'buildingId' in selectedBuilding && roomQueryForm.buildingId !== selectedBuilding['buildingId']) {
    roomQueryForm.buildingId = selectedBuilding['buildingId']
    roomQueryForm.buildingName = selectedBuilding['buildingName']
  }
}

const onBack = () => {
  emit('roomSelectedEvent')
}
</script>

<style lang="scss">
</style>
